import { useEffect, useRef, useState } from "react";
import { Textarea, TextareaProps } from "../ui/textarea"
import clsx from "clsx";
import { useInputFocusContext } from "@/context/InputFocusContext";

interface Props extends React.TextareaHTMLAttributes<HTMLTextAreaElement> {
  defaultValue: string;
  value: string;
  onChange: (event: React.ChangeEvent<HTMLTextAreaElement>) => void;
  placeholder?: string;
  className?: string;
  height?: number;
  autoHeight?: boolean;
  enterKey?: boolean;
  other?: TextareaProps;
  onListenerBlur?(e: React.ChangeEvent<HTMLTextAreaElement>): void;
  enterDown?(): void;
  spellCheck?: boolean;
}

export const TextArea = (props: Props) => {
  const {
    value,
    placeholder = 'Placeholder',
    height = 36,
    onChange,
    enterKey = false,
    defaultValue,
    className,
    onListenerBlur,
    enterDown,
    spellCheck = true,
    name,
    autoHeight
  } = props

  const [textareaHeight] = useState(`${height}px`);

  const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    onChange(e);
    adjustTextareaHeight(e.target);
  };

  const adjustTextareaHeight = (textarea: HTMLTextAreaElement) => {
    textarea.style.height = textareaHeight;
    textarea.style.height = `${textarea.scrollHeight}px`;
  };

  const handleSubmitName = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
    if (!!e.target.value) {
      if (onListenerBlur) {
        onListenerBlur(e)
      }
    } else if (!e.target.value.trim()) {
      e.target.value = defaultValue
      onChange(e)
    }
  }

  const { registerInput } = useInputFocusContext();
  const inputRef = useRef(null);

  const handleStopWrap = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
    if (enterKey) {
      if (event.key === 'Enter') {
        if (enterDown) {
          event.preventDefault();
          enterDown()
        }
      };
    }
  }

  useEffect(() => {
    registerInput(name, inputRef.current);
  }, [name, registerInput]);

  return <Textarea
    placeholder={placeholder}
    value={value}
    onChange={handleInputChange}
    onBlur={handleSubmitName}
    style={{ height: autoHeight ? 'auto' : textareaHeight }}
    onKeyDown={handleStopWrap}
    className={clsx(' min-h-6 resize-none border-none p-1 text-xl max-h-28', className)}
    spellCheck={spellCheck}
    // onClick={(e) => e.stopPropagation()}
    name={name}
    ref={inputRef}
  />

}